<?php

namespace app\models\cmiot;

use app\models\Util;
use Yii;
use yii\base\Exception;
use yii\base\Model;

/**
 *  中移物联网接口
 * Class Api
 * @package app\models\cmiot
 */
class Api extends Model
{
    /**
     * @var string 服务器
     */
    private $server;
    /**
     * @var string 应用编号
     */
    private $APPID;
    /**
     * @var string 集团编码
     */
    private $ECID;
    /**
     * @var string 接入密码
     */
    private $PASSWORD;

    /**
     * @inheritdoc
     * @param string $ispData isp.data
     */
    public function __construct($ispData)
    {
        $json = json_decode($ispData, true);
        $this->server = isset($json['server']) ? $json['server'] : '';
        $this->APPID = isset($json['APPID']) ? $json['APPID'] : '';
        $this->ECID = isset($json['ECID']) ? $json['ECID'] : '';
        $this->PASSWORD = isset($json['PASSWORD']) ? $json['PASSWORD'] : '';
        parent::__construct([]);
    }

    use ApiTrait;

    /**
     * 生成事务编码
     * @return string
     */
    private function makeTransId()
    {
        return $this->APPID . date('YmdHis') . Util::randomStr(8, 1);
    }

    /**
     * 生成令牌
     * @param $transId string 事务编码
     * @return string
     */
    private function makeToken($transId)
    {
        return hash('sha256', $this->APPID . $this->PASSWORD . $transId);
    }

    /**
     * 调用方法，返回JSON
     * @param string $uri 接口地址
     * @param array $params 数据
     * @param string $ebid 能力编码
     * @return array
     * @throws Exception
     */
    private function post($uri, $ebid, $params)
    {
        $params['appid'] = $this->APPID;
        $params['transid'] = $this->makeTransId();
        $params['ebid'] = $ebid;
        $params['token'] = $this->makeToken($params['transid']);

        $url = $this->server . $uri;
        $data = http_build_query($params);

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER, [
            'Content-Type: application/x-www-form-urlencoded',
        ]);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $resp = curl_exec($curl);
        $error_no = curl_errno($curl);
        $error = curl_error($curl);
        curl_close($curl);

        if (YII_DEBUG) {
            Yii::warning($url, 'cmiot');
            Yii::warning($data, 'cmiot');
            Yii::warning($resp, 'cmiot');
        }
        if ($error_no != 0) {
            throw new Exception('接口错误：' . $error_no . '：' . $error, 999);
        }

        $json = json_decode($resp, true);
        if ($json === null) {
            throw new Exception('无法解析接口返回数据：' . $resp, 999);
        }

        if (!isset($json['status'])) {
            throw new Exception('返回数据异常：' . $resp, 999);
        }
        if ($json['status'] != 0) {
            throw new Exception('业务失败：' . $json['message'], $json['status']);
        }
        return $json['result'];
    }

    /**
     * 调用方法，返回内容
     * @param string $uri 接口地址
     * @param array $params 数据
     * @param string $ebid 能力编码
     * @return string
     * @throws Exception
     */
    private function post2($uri, $ebid, $params)
    {
        $params['appid'] = $this->APPID;
        $params['transid'] = $this->makeTransId();
        $params['ebid'] = $ebid;
        $params['token'] = $this->makeToken($params['transid']);

        $url = $this->server . $uri;
        $data = http_build_query($params);

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER, [
            'Content-Type: application/x-www-form-urlencoded',
        ]);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $resp = curl_exec($curl);
        $error_no = curl_errno($curl);
        $error = curl_error($curl);
        curl_close($curl);

        if (YII_DEBUG) {
            Yii::warning($url, 'cmiot');
            Yii::warning($data, 'cmiot');
            Yii::warning($resp, 'cmiot');
        }
        if ($error_no != 0) {
            throw new Exception('接口错误：' . $error_no . '：' . $error, 999);
        }

        return $resp;
    }
}
